import { App, mall, navigate, toast } from '../../../../library/api/index'
Page({
  data: {
    navMe: 'on',
    tip: 'blank',
    tipData: {},
    orders: [],
    redeem_status_code: 0,
    redeem_status_message: '',
    redeem: {},
    validdate: null,
    invaliddate: null,
  },
  onLoad: function(e) {
    App.jice.onLoad(e)
  },
  onReady: function() {
    App.jice.track('page', {
      pagepath: '/pages/me/order/list/index',
      pageTitle: '个人中心-订单-列表',
      pageType: 'view'
    })
    App.logger({
      type: App.G.view,
      channel: App.G.channel,
      target: '个人中心-订单-列表'
    })
  },
  onShow: function() {
    this.getOrders()
    App.jice.track('appshow')
  },
  getOrders: function() {
    toast.show(2000)
    mall.getOrders(r => {
      toast.close()
      if(r.code == 200) {
        this.setData({
          orders: r.data
        })
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      this.showErrorTip(`系统错误[${r.message}]，请稍后再试~`)
    })
  },
  goSettlement: function(e) {
    navigate.to(`/pages/me/order/settlement/index?order_id=${e.currentTarget.dataset.orderId}`)
  },
  goReturn: function(e) {
    console.log(e)
    let type = e.currentTarget.dataset.orderType
    navigate.to(`/pages/me/order/return/index?order_id=${e.currentTarget.dataset.orderId}`)
  },
  viewReturn: function(e) {
    console.log(e)
    let returnStatus = e.currentTarget.dataset.returnStatus
    let returnOrderId = e.currentTarget.dataset.orderId
    let type = e.currentTarget.dataset.orderType
    if(returnStatus == mall.ReturnStatus.NotAudit) {
      // 退货申请提交未审核
      this.showErrorTip('已经收到退货申请，请您耐心等待商家处理！')
      return
    }
    if(returnStatus == mall.ReturnStatus.AuditSuccess) {
      // 审核成功,前往填写返回信息
      navigate.to(`/pages/me/order/return/express/index?order_id=${returnOrderId}`)
    }
    if(returnStatus == mall.ReturnStatus.SendBackGoods) {
      // 审核成功,用户提交了退货信息
      this.showErrorTip('退货的物流信息已收到，请您耐心等待商家处理！')
      return
    }
    if(returnStatus == mall.ReturnStatus.AudiFailure) {
      // 审核失败,查询失败原因
      mall.getReturnStatus(returnOrderId, r => {
        console.log(r)
        if(r.code == 200) {
          this.showErrorTip(`您的退货申请未通过，拒绝原因：${r.data.auditreason}`)
        } else {
          this.showErrorTip(r.data)
        }
      }, r => {
        console.log(r)
        this.showErrorTip('系统错误，请稍候再试！')
      })
    }
    if(returnStatus == mall.ReturnStatus.ReceiveReturn) {
      // 收到退货
      this.showErrorTip('商家已确认收货，正在为您退款中！')
      return
    }
    if(returnStatus == mall.ReturnStatus.Refund) {
      // 弹框提示退款文案
      let returnFee = e.currentTarget.dataset.returnFee
      this.setData({
        tip: 'return_tip',
        tipData: `货款${returnFee}元已退回至您的微信账户请注意查收！`
      })
      return
    }
  },
  confirm: function(e) {
    let orderId = e.currentTarget.dataset.orderId
    let orderType = e.currentTarget.dataset.orderType
    toast.show(5000)
    mall.confirmReceived(orderId, orderType, r => {
      toast.close()
      if(r.code == 200) {
        //待产包订单需要单独处理一下查看是否有提货券
        if(orderType == mall.OrderType.PreparePackage) {
          var hasRedeem = false
          for(let i = 0; i < this.data.orders.length; i++) {
            if(this.data.orders[i]._id == orderId) {
              for(let j = 0; j < this.data.orders[i].products.length; j++) {
                if(this.data.orders[i].products[j]['type'] == 2) {
                  hasRedeem = true
                  break
                }
              }
            }
          }
          if(hasRedeem) {
            mall.hasRedeem(r => {
              if(r.code >= 200 && r.code < 300) {
                this.setData({
                  redeem_status_code: r.code,
                  redeem_status_message: r.data,
                  redeem: r.result
                })
                this.setData({
                  tip: 'redeem_tip',
                  tipData: {
                    code: this.data.redeem.code,
                    name: this.data.redeem.products.name,
                    validdate: this.data.redeem.validdate,
                    invaliddate: this.data.redeem.invaliddate,
                    img: this.data.redeem.products.mainimg
                  }
                })
              } else {
                this.showErrorTip(r.data)
              }
            }, r => {
              console.log(r)
              this.showErrorTip('系统错误，请稍后再试')
            })
          }
        }
        this.getOrders()
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      this.showErrorTip(`系统错误[${r.message}]，请稍后再试~`)
    })
  },
  pickup: function() {
    this.setData({
      tip: 'blank',
      tipData: ''
    })
  },
  showErrorTip: function(message) {
    this.setData({
      tip: 'error_tip',
      tipData: message
    })
  },
  closeTip: function() {
    this.setData({
      tip: 'blank',
      tipData: ''
    })
  },
  minus: function(e) {
    let pid = e.currentTarget.dataset.pid
    let orderId = e.currentTarget.dataset.orderId
    for(let i = 0; i < this.data.orders.length; i++) {
      if(this.data.orders[i]._id == orderId) {
        for(let m = 0; m < this.data.orders[i].products.length; m++) {
          if(this.data.orders[i].products[m].id == pid) {
            this.data.orders[i].products[m].count -= 1
            if(this.data.orders[i].products.length > 1 && this.data.orders[i].products[m].count == 0) {
              this.data.orders[i].products.splice(m, 1)
            } else if(this.data.orders[i].products.length == 1 && this.data.orders[i].products[m].count == 0) {
              navigate.redirect('/pages/mall/milk/index')
              return
            }
            break
          }
        }
        break
      }
    }
    let order = {}
    for(let i = 0; i < this.data.orders.length; i++) {
      if(this.data.orders[i]._id == orderId) {
        let total = 0
        let fee = 0
        for(let m = 0; m < this.data.orders[i].products.length; m++) {
          total += this.data.orders[i].products[m].count
          fee += this.data.orders[i].products[m].count * this.data.orders[i].products[m].my_price
        }
        this.data.orders[i].count = total
        this.data.orders[i].fee = (fee * 100) / 100
        order = this.data.orders[i]
      }
    }

    this.setData({
      orders: this.data.orders
    })

    mall.saveOrder({
      type: order.type,
      address: JSON.stringify({
        name: order.reciver,
        tel: order.recivetel,
        address: order.reciveaddress
      }),
      products: JSON.stringify(order.products)
    }, r => {
      if(r.code == 200) {
        console.log(r)
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  },
  add: function(e) {
    let pid = e.currentTarget.dataset.pid
    let orderId = e.currentTarget.dataset.orderId
    for(let i = 0; i < this.data.orders.length; i++) {
      if(this.data.orders[i]._id == orderId) {
        for(let m = 0; m < this.data.orders[i].products.length; m++) {
          if(this.data.orders[i].products[m].id == pid) {
            this.data.orders[i].products[m].count += 1
            break
          }
        }
        break
      }
    }
    let order = {}
    for(let i = 0; i < this.data.orders.length; i++) {
      if(this.data.orders[i]._id == orderId) {
        let total = 0
        let fee = 0
        for(let m = 0; m < this.data.orders[i].products.length; m++) {
          total += this.data.orders[i].products[m].count
          fee += this.data.orders[i].products[m].count * this.data.orders[i].products[m].my_price
        }
        this.data.orders[i].count = total
        this.data.orders[i].fee = (fee * 100) / 100
        order = this.data.orders[i]
      }
    }

    this.setData({
      orders: this.data.orders
    })

    mall.saveOrder({
      type: order.type,
      address: JSON.stringify({
        name: order.reciver,
        tel: order.recivetel,
        address: order.reciveaddress
      }),
      products: JSON.stringify(order.products)
    }, r => {
      if(r.code == 200) {
        console.log(r)
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      console.log(r)
      this.showErrorTip(`系统错误，请稍后再试~`)
    })
  }
})